package com.dtagri.fjwlw.util;

import java.io.File;

import com.dtagri.fjwlw.api.ApiHttpClient;
import com.dtagri.fjwlw.api.FJwlwApi;
import com.dtagri.fjwlw.bean.UpdataInfo;


import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

public class UpdateUtil {

	private Context context;
	public static final int UPDATA_CLIENT = 0;
	public static final int GET_UNDATAINFO_ERROR = 1;
	public static final int DOWN_ERROR = 2;
	public static final int START_MAIN = 3;
	public static final int PS_PROCESS = 4;
	public static final int PS_MAX = 5;
	public static final int PS_COMPLETE = 6;
	public static final int UPDATA_OTHER_CLIENT = 7;
	public static final int UPDATA_OTHER_WCC_APK = 8;
	public static final int DOWNLOAD_SJZW_APK = 9;
	private UpdataInfo info = null;
	private final String tag = "UpdateUtil";
	private ProgressDialog pd = null;
	private File file = null;
	private MyHandler handler;
	private String method;
	// 通知对话框
	private Dialog noticeDialog;
	// 提示语
	private String updateMsg = "";
//	private SharedPreferencesData data;

	public UpdateUtil(Context con, String num) {
		this.context = con;
		this.method = num;
		handler = new MyHandler();
		pd = new ProgressDialog(context);
		pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		pd.setMessage("正在下载中....");
		pd.setCanceledOnTouchOutside(false);

		new Thread(new Update(context, handler, method)).start();

	}

	class MyHandler extends Handler {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case UPDATA_CLIENT:
				// 对话框通知用户升级程序
				info = (UpdataInfo) msg.getData().getSerializable("updatainfo");
				updateMsg = info.getUpdateContent();
			
				if (updateMsg.equals("")) {
					updateMsg = "发现新版本,是否马上升级?";
				}
//				data= new SharedPreferencesData(context);
				//设置服务器端version到spdata以便升级更新判断是否出现引导页,发现版本号不同是将其保存下来
//				if (data.getVersionData()!=info.getVersion()) {
//					data.setVersionData(info.getVersion());
//				}
				showNoticeDialog();
				break;
			case GET_UNDATAINFO_ERROR:
				// 服务器超时
				Toast.makeText(context, "网络连接失败,请检查网络连接...", Toast.LENGTH_SHORT)
						.show();
				if (pd != null)
					pd.dismiss();
				break;
			case DOWN_ERROR:
				// 下载apk失败
				Toast.makeText(context, "下载新版本失败", Toast.LENGTH_SHORT).show();
				if (pd != null)
					pd.dismiss();
				break;
			case START_MAIN:
				if (method.equals("index")) {

				} else {
					Toast.makeText(context, "当前版本无需更新", 2000)
							.show();
				}
				break;

			case PS_PROCESS:
				pd.setProgress(msg.getData().getInt("total"));
				break;

			case PS_MAX:
				pd.setMax(msg.getData().getInt("max"));
				break;
			case PS_COMPLETE:
				pd.dismiss();
				break;
			}
		}
	};

	/**
	 * 显示版本更新通知对话框
	 */
	private void showNoticeDialog() {
		AlertDialog.Builder builder = new Builder(context);
		builder.setMessage("更新日志：" + updateMsg);
		builder.setPositiveButton("立即更新", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {

				dialog.dismiss();
				downLoadApk();
			}
		});
		builder.setNegativeButton("以后再说", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		noticeDialog = builder.create();
		noticeDialog.show();
	}

	/*
	 * 从服务器中下载APK
	 */

	protected void downLoadApk() {
		pd.show();
		new Thread() {
			@Override
			public void run() {
				try {
					System.out.println("-------开始下载apk--------");
					file = DownLoadManager.getFileFromServer(info.getUrl(), pd,
							handler,Update.UPDATE_FILE_NAME);
					sleep(300);
					installApk(file);
				} catch (Exception e) {
//					Log.d("tag",
//							info.getUrl() + "---download exception--"
//									+ e.toString());
					Message msg = new Message();
					msg.what = DOWN_ERROR;
					handler.sendMessage(msg);
					e.printStackTrace();
				}
			}
		}.start();
	}

	// 安装apk
	protected void installApk(File file) {
		Intent intent = new Intent();
		// 执行动作
		intent.setAction(Intent.ACTION_VIEW);
		// 执行的数据类型
		intent.setDataAndType(Uri.fromFile(file),
				"application/vnd.android.package-archive");
		context.startActivity(intent);
	}

	private boolean isSDCard() {

		String sdStatus = Environment.getExternalStorageState();
		Log.d(tag, "status--" + sdStatus);
		if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
			Toast.makeText(context, "请检查SD卡是否正常插入!", Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}
}
